package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.BrandTO;
import com.atguigu.common.to.es.SkuESModel;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.search.config.SearchApplication;
import com.atguigu.gulimall.search.constant.EsConstant;
import com.atguigu.gulimall.search.feign.ProductFeignService;
import com.atguigu.gulimall.search.service.MallSearchService;
import com.atguigu.gulimall.search.vo.AttrRespVO;
import com.atguigu.gulimall.search.vo.SearchParam;
import com.atguigu.gulimall.search.vo.SearchResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author baiWT
 * @Description
 * @Date 2022/3/29 17:16
 **/
@Slf4j
@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Resource
    private RestHighLevelClient client;

    @Resource
    private ProductFeignService productFeignService;

    /**
     * 根据检索条件去es中进行检索
     * @param searchParam
     * @return
     */
    @Override
    public SearchResult search(SearchParam searchParam) {
        //1、动态构建出需要的DSL语句
        SearchResult result = null;
        //1、准备检索请求
        SearchRequest searchRequest = buildSearchRequest(searchParam);

        try {
            //2、执行检索请求
            SearchResponse response = client.search(searchRequest, SearchApplication.COMMON_OPTIONS);

            //3、分析响应数据封装成我们需要的格式
            result = buildSearchResult(response,searchParam);
        }catch (Exception e){

        }
        return result;
    }

    /**
     * 准备检索请求
     * #模糊匹配，过滤(按照属性、分类、品牌、价格区间、库存)，排序，分页，高亮，聚合分析
     * @return
     */
    private SearchRequest buildSearchRequest(SearchParam searchParam) {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();//构建DSL语句

        /**
         * 模糊匹配，过滤(按照属性、分类、品牌、价格区间、库存)
         */
        //1、构建bool - query
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //1.1、must-模糊匹配
        if (!StringUtils.isEmpty(searchParam.getKeyword())){
            boolQuery.must(QueryBuilders.matchQuery("skuTitle",searchParam.getKeyword()));
        }
        //1.2、bool - filter 按照三级分类id查询
        if (searchParam.getCatelog3Id()!=null){
            boolQuery.filter(QueryBuilders.termQuery("catelogId",searchParam.getCatelog3Id()));
        }
        //1.2、bool - filter 按照品牌id查询
        if (searchParam.getBrandId() != null && searchParam.getBrandId().size() > 0){
            boolQuery.filter(QueryBuilders.termsQuery("brandId",searchParam.getBrandId()));
        }
        //1.2、bool - filter 按照所有指定的属性查询
        if (searchParam.getAttrs() != null && searchParam.getAttrs().size() > 0){

            for (String attrStr : searchParam.getAttrs()){
                BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
                //attr = 1_5寸:8寸
                String[] s = attrStr.split("_");
                String attrId = s[0];//检索的id
                String[] attrValues = s[1].split(":"); //这个属性检索的值

                nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId",attrId));
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue",attrValues));
                //关键点: 每一个nested都必须生成一个nested查询
                NestedQueryBuilder nestedQueryBuilder = QueryBuilders.nestedQuery("attrs",nestedBoolQuery, ScoreMode.None);
                boolQuery.filter(nestedQueryBuilder);
            }


        }

        //1.2、bool - filter 按照库存有是否查询
        boolQuery.filter(QueryBuilders.termsQuery("hasStock",searchParam.getHasStock() == 1));

        //1.2、bool - filter 按照价格区间进行检索
        if (!StringUtils.isEmpty(searchParam.getSkuPrice())){
            /**
             * 价格区间
             * &price=1_500
             * &price=_500
             * &price=500_
             */
            RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("skuPrice");

            String[] s = searchParam.getSkuPrice().split("_");
            System.out.println("s----"+searchParam.getSkuPrice()+"---"+s.length);

//            if (s.length == 2){
//                //区间
//                rangeQueryBuilder.gte(s[0]).lte(s[1]);
//            }else if (s.length == 1){
                System.out.println("执行了");
                if (searchParam.getSkuPrice().startsWith("_")){
                    rangeQueryBuilder.lte(s[0]);
                }else if (searchParam.getSkuPrice().endsWith("_")){
                    rangeQueryBuilder.gte(s[0]);
                }else{
                    rangeQueryBuilder.gte(s[0]).lte(s[1]);
                }


//            }

            boolQuery.filter(rangeQueryBuilder);
        }

        //把所有条件拿来封装
        sourceBuilder.query(boolQuery);

        /**
         * 排序，分页，高亮
         */
        //2.1、排序
        if (!StringUtils.isEmpty(searchParam.getSort())){
            String sort = searchParam.getSort();
            String[] s = sort.split("_");
            SortOrder order = s[1].equalsIgnoreCase("asc")? SortOrder.ASC:SortOrder.DESC;
            sourceBuilder.sort(s[0],order);
        }

        //2.2、分页
        //from = (pageNum-1)*size
        sourceBuilder.from((searchParam.getPageNum()-1)*EsConstant.PRODUCT_PAGESIZE);
        sourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);

        //2.3、高亮
        if (!StringUtils.isEmpty(searchParam.getKeyword())){
            HighlightBuilder builder = new HighlightBuilder();
            builder.field("skuTitle");
            builder.preTags("<b style='color:red'>");
            builder.postTags("</b>");
            sourceBuilder.highlighter(builder);
        }

        /**
         * 聚合分析
         */
        //1、品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId").size(50);
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        //TODO 聚合brand
        sourceBuilder.aggregation(brand_agg);

        //2、分类聚合
        TermsAggregationBuilder catelog_agg = AggregationBuilders.terms("catelog_agg").field("catelogId").size(20);
        catelog_agg.subAggregation(AggregationBuilders.terms("catelog_name_agg").field("catelogName").size(1));
        //TODO 聚合分类
        sourceBuilder.aggregation(catelog_agg);

        //3、属性聚合
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg","attrs");
        //聚合出当前的所有attrId
        TermsAggregationBuilder attr_id = AggregationBuilders.terms("attr_id").field("attrs.attrId");
        attr_id.subAggregation(AggregationBuilders.terms("attr_name").field("attrs.attrName").size(1));
        attr_id.subAggregation(AggregationBuilders.terms("attr_value").field("attrs.attrValue").size(50));
        attr_agg.subAggregation(attr_id);
        //TODO 聚合属性
        sourceBuilder.aggregation(attr_agg);

        System.out.println("构建的dsl：："+sourceBuilder.toString());

        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX},sourceBuilder);
        return searchRequest;
    }

    /**
     * 构建结果数据
     * @param response
     * @return
     */
    private SearchResult buildSearchResult(SearchResponse response,SearchParam searchParam) {
        SearchResult searchResult = new SearchResult();
        SearchHits hits = response.getHits();
        //1、返回的所有查询到的商品
        List<SkuESModel> esModels = new ArrayList<>();
        if (hits.getHits() != null && hits.getHits().length > 0){
            for (SearchHit hit : hits){
                String sourceAsString = hit.getSourceAsString();
                SkuESModel esModel = JSON.parseObject(sourceAsString, SkuESModel.class);
                if (!StringUtils.isEmpty(searchParam.getKeyword())) {
                    String skuTitle = hit.getHighlightFields().get("skuTitle").getFragments()[0].toString();
                    esModel.setSkuTitle(skuTitle);
                }
                esModels.add(esModel);
            }
        }
        searchResult.setSkuList(esModels);

        //2、当前所有商品涉及到的所有属性信息
        ParsedLongTerms catelog_agg = response.getAggregations().get("catelog_agg");
        List<SearchResult.CatelogVO> catelogVOS = new ArrayList<>();
        List<? extends Terms.Bucket> buckets = catelog_agg.getBuckets();
        for(Terms.Bucket bucket : buckets){
            SearchResult.CatelogVO catelogVO = new SearchResult.CatelogVO();
            //得到分类id
            String keyAsString = bucket.getKeyAsString();
            catelogVO.setCatelogId(Long.parseLong(keyAsString));

            //得到分类名
            ParsedStringTerms catelog_name_agg = bucket.getAggregations().get("catelog_name_agg");
            String catelog_name = catelog_name_agg.getBuckets().get(0).getKeyAsString();
            catelogVO.setCatelogName(catelog_name);
            catelogVOS.add(catelogVO);
        }
        searchResult.setCatelogs(catelogVOS);

        //3、当前所有商品涉及到的所有品牌信息
        ParsedLongTerms brandAgg = response.getAggregations().get("brand_agg");
        List<SearchResult.BrandVO> brands = brandAgg.getBuckets().stream().map(bucket -> {
            //得到品牌的id
            long brandId = bucket.getKeyAsNumber().longValue();
            //得到品牌的名字
            ParsedStringTerms brandNameAgg = bucket.getAggregations().get("brand_name_agg");
            String brandName = brandNameAgg.getBuckets().get(0).getKeyAsString();
            //得到品牌的图片
            ParsedStringTerms brandImgAgg = bucket.getAggregations().get("brand_img_agg");
            String brandImg = brandImgAgg.getBuckets().get(0).getKeyAsString();
            SearchResult.BrandVO brandVO = new SearchResult.BrandVO();
            brandVO.setBrandId(brandId);
            brandVO.setBrandName(brandName);
            brandVO.setBrandImg(brandImg);
            return brandVO;
        }).collect(Collectors.toList());
        searchResult.setBrands(brands);

        //4、当前所有商品涉及到的所有分类信息
        ParsedNested attrAgg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attrIdAgg = attrAgg.getAggregations().get("attr_id");
        List<SearchResult.AttrVO> attrs = attrIdAgg.getBuckets().stream().map(bucket -> {
            long attrId = bucket.getKeyAsNumber().longValue();
            ParsedStringTerms attrNameAgg = bucket.getAggregations().get("attr_name");
            // 根据id分类后肯定是同一类，只可能有一种名字，所以直接取第一个bucket
            String attrName = attrNameAgg.getBuckets().get(0).getKeyAsString();
            // 根据id分类后肯定是同一类，但是可以有多个值，所以会有多个bucket，把所有值组合起来
            ParsedStringTerms attrValueAgg = bucket.getAggregations().get("attr_value");
            List<String> attrValue = attrValueAgg.getBuckets().stream().map(b -> b.getKeyAsString()).collect(Collectors.toList());
            SearchResult.AttrVO attrVO = new SearchResult.AttrVO();
            attrVO.setAttrId(attrId);
            attrVO.setAttrName(attrName);
            attrVO.setAttrValue(attrValue);
            return attrVO;
        }).collect(Collectors.toList());
        searchResult.setAttrs(attrs);

        //5、分页信息
        searchResult.setTotalCount(hits.getTotalHits().value);
        // 每页大小
        searchResult.setPageSize(EsConstant.PRODUCT_PAGESIZE);
        // 总页数
        searchResult.setTotalPage((searchResult.getTotalCount() + EsConstant.PRODUCT_PAGESIZE - 1) / EsConstant.PRODUCT_PAGESIZE);
        // 当前页码
        int pageNum = searchParam.getPageNum() == null ? 1 : searchParam.getPageNum();
        searchResult.setCurrPage(pageNum);
        // 构建页码导航,以当前页为中心，连续5页
        ArrayList<Integer> pageNavs = new ArrayList<>();
        for (int i = pageNum - 2; i <= pageNum + 2; ++i) {
            if (i <= 0) {
                continue;
            }
            if (i >= searchResult.getTotalPage()) {
                break;
            }
            pageNavs.add(i);
        }
        searchResult.setPageNavs(pageNavs);

        //6、构建面包屑导航功能

        List<SearchResult.BreadCrumbsVO> breadCrumbsVOS = new LinkedList<>();
        /**
         * 构建面包屑导航--参数品牌部分
         */
        List<Long> ids = searchParam.getBrandId();
        if (!CollectionUtils.isEmpty(ids)) {
            R res = productFeignService.getBatch(ids);
            if (res.getCode() == 0) {
                List<BrandTO> brandTOS = res.getData(new TypeReference<List<BrandTO>>() {});
                brandTOS.forEach(brandTO -> {
                    SearchResult.BreadCrumbsVO crumb = new SearchResult.BreadCrumbsVO();
                    crumb.setAttrName("品牌");
                    crumb.setAttrValue(brandTO.getName());
                    // 请求参数中去掉当前属性之后的链接地址
                    String link = searchParam.getQueryString().replace("&brandId=" + brandTO.getBrandId(), "").replace("brandId=" + brandTO.getBrandId(), "");
                    crumb.setLink("http://search.gulimall.com/list.html?" + link);
                    breadCrumbsVOS.add(crumb);
                });
            } else {
                log.warn("ESSearch调用gulimall-product/brand/info/batch失败");
            }
        }

        /**
         * 构建面包屑导航，三级分类部分
         */

        /**
         * 构建面包屑导航--规格参数部分
         * 从请求参数规格参数部分，
         * 请求参数中有规格参数部分条件，才构建
         // &attrs=1_陶瓷:铝合金&attrs=2_anzhuo:apple
         */
        List<String> queryAttrs = searchParam.getAttrs();
        if (!CollectionUtils.isEmpty(queryAttrs)) {
            List<SearchResult.BreadCrumbsVO> crumbsVOS = queryAttrs.stream().map(attrStr -> {
                // id_value
                String[] attrInfo = attrStr.split("_");
                SearchResult.BreadCrumbsVO breadCrumbsVO = new SearchResult.BreadCrumbsVO();
                breadCrumbsVO.setAttrValue(attrInfo[1]);
                // 请求参数中去掉当前属性之后的链接地址
                String link = "";
                try {
                    // request对路径进行了编码。我们得先把自己的参数编码。才能在路径正正确匹配并替换
                    String encode = URLEncoder.encode(attrStr, "utf-8");
                    // java编码后，空格会被替换为 + ，而浏览器会编码为 %20；英文()会被编码成%28,%29，而浏览器不会编码英文()
                    // 所以我们还得把+替换为浏览器的规则
                    encode = encode.replace("+", "%20").replace("%28", "(").replace("%29", ")");
                    // 去掉 &attrs=1_陶瓷
                    URLDecoder.decode(searchParam.getQueryString(), "iso-8859-1");
                    link = searchParam.getQueryString().replace("&attrs=" + encode, "").replace("attrs=" + encode, "");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                breadCrumbsVO.setLink("http://search.gulimall.com/list.html?" + link);
                // 保存请求参数中的attrId
                searchResult.getParamAttrIds().add(Long.parseLong(attrInfo[0]));
                // 远程调用
                try {
                    R r = productFeignService.info(Long.valueOf(attrInfo[0]));
                    if (r.getCode() == 0) {
                        AttrRespVO attrRespVO = r.getData("attr", AttrRespVO.class);
                        breadCrumbsVO.setAttrName(attrRespVO.getAttrName());
                    }
                } catch (Exception e) {
                    log.error("gulimall-search调用gulimall-product根据attrId查询attrInfo失败：{}", e);
                }
                return breadCrumbsVO;
            }).collect(Collectors.toList());
            breadCrumbsVOS.addAll(crumbsVOS);

        }
        // 保存所有面包屑
        searchResult.setBreadCrumbsNavs(breadCrumbsVOS);

        return searchResult;
    }


}
